﻿
// global properties
var stage;
var currentTick = 0;
var arrayImages = new Array();
var loadedImgNumber = 0;

// for welcome screen
var loadingC2Img;
var loadingTextImg;
var loadingMusicImg;

// for other screen
var stageSprite;
var topLightImgs;
var logoSprite;
var welcomeCha;
var tvcCha;

// for character lap
var welcomeLapSpite;
var tvcStartSpite;
var tvcLapSpite;

var tickTVC = -1;

/**
* Init handler
*/

$(document).ready(function () {
    log("Width: " + window.innerWidth + " - Height: " + window.innerHeight + "- Ratio: " + window.devicePixelRatio);

    if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
        var msViewportStyle = document.createElement("style");
        msViewportStyle.appendChild(
            document.createTextNode(
                "@-ms-viewport{width:auto!important}"
            )
        );
        document.getElementsByTagName("head")[0].
            appendChild(msViewportStyle);
    }

    initLoadingScreen();

    $("#btnHome").click(welcomeVideoStart);
    $("#btnVideo").click(tvcVideoStart);
    $("#btnMusic").click(fullsongVideoStart);
});




/**
* Init welcome handler
*/

function initLoadingScreen() {
    arrayImages[0] = new Image();
    arrayImages[0].onload = handleLoadingImageLoad;
    arrayImages[0].onerror = handleImageError;
    arrayImages[0].src = "index_files/Chai_C2.png";

    arrayImages[1] = new Image();
    arrayImages[1].onload = handleLoadingImageLoad;
    arrayImages[1].onerror = handleImageError;
    arrayImages[1].src = "index_files/music.png";

    arrayImages[2] = new Image();
    arrayImages[2].onload = handleLoadingImageLoad;
    arrayImages[2].onerror = handleImageError;
    arrayImages[2].src = "index_files/loading.png";
}


/**
* Handle loading image for welcome
*/
function handleLoadingImageLoad(e) {
    loadedImgNumber++;

    if (loadedImgNumber == 3) {
        startWelcomeScreen();
    }
}


/**
* Handle loading error
*/
function handleImageError(e) {
    log("Error Loading Image : " + e.target.src);
}


/**
* Initilale Welcome Screen
*/
function startWelcomeScreen() {
    $(".loading").hide();
    var canvas = document.getElementById("canvas");
    stage = new createjs.Stage(canvas);

    loadingC2Img = new createjs.Bitmap(arrayImages[0]);
    loadingC2Img.regX = 85;
    loadingC2Img.regY = 460;
    loadingC2Img.x = 512;
    loadingC2Img.y = 570;
    loadingC2Img.scaleX = 0.8;
    loadingC2Img.scaleY = 0.8;
    stage.addChild(loadingC2Img);

    loadingMusicImg = new createjs.Bitmap(arrayImages[1]);
    loadingMusicImg.regX = 85;
    loadingMusicImg.regY = 217;
    loadingMusicImg.x = 512;
    loadingMusicImg.y = 150;
    stage.addChild(loadingMusicImg);

    loadingTextImg = new createjs.Bitmap(arrayImages[2]);
    loadingTextImg.regX = 87;
    loadingTextImg.regY = 30;
    loadingTextImg.x = 512;
    loadingTextImg.y = 150;
    stage.addChild(loadingTextImg);

    createjs.Ticker.setFPS(12);
    createjs.Ticker.addEventListener("tick", tickLoading);

    initMainScreen();
}


/**
* Tick Handler
*/
var angle = 5;
function tickLoading() {
	console.log(angle);
    currentTick += 1;
    loadingC2Img.rotation += angle;
    if (loadingC2Img.rotation == 10)
        angle = -5;
    else if (loadingC2Img.rotation == -10)
        angle = 5;

    if (loadingMusicImg.y > 0)
        loadingMusicImg.y -= 13;
    else {
        if (currentTick == 1) {
            loadingMusicImg.y = 150;
        }
    }


    if (currentTick > 12)
        currentTick = 0;
    stage.update();
}


/**
* Handle loading image for main stage
*/
function initMainScreen() {
    $(".buttons").show();
    
    arrayImages[3] = new Image();
    arrayImages[3].onload = handleImageLoad;
    arrayImages[3].onerror = handleImageError;
    arrayImages[3].src = "index_files/light.png";

    arrayImages[4] = new Image();
    arrayImages[4].onload = handleImageLoad;
    arrayImages[4].onerror = handleImageError;
    arrayImages[4].src = "index_files/logo.png";

    arrayImages[5] = new Image();
    arrayImages[5].onload = handleImageLoad;
    arrayImages[5].onerror = handleImageError;
    arrayImages[5].src = "index_files/stage_tablet.png";
    
    arrayImages[6] = new Image();
    arrayImages[6].onload = handleImageLoad;
    arrayImages[6].onerror = handleImageError;
    arrayImages[6].src = "index_files/welcome_lap_SH.png";
    
    arrayImages[7] = new Image();
    arrayImages[7].onload = handleImageLoad;
    arrayImages[7].onerror = handleImageError;
    arrayImages[7].src = "index_files/startTvc_S.png";
}



/**
* Handle loading image for main stage
*/
function handleImageLoad(e) {
    loadedImgNumber++;

    if (loadedImgNumber == 8) {
        startMainScreen();
    }
}


/**
* Initilale Main Screen
*/
function startMainScreen() {
    reset();
    stage = new createjs.Stage(canvas);

    log("Start main stage");
    
    log("Add stage");
    var stageSpriteSheet = new createjs.SpriteSheet({
        //image to use
        images: [arrayImages[5]],
        //width, height & registration point of each sprite
        frames: [
            [0, 1, 867, 90],
            [0, 1, 867, 90],
            [0, 1, 867, 90],
            [0, 103, 867, 90],
            [0, 103, 867, 90],
            [0, 103, 867, 90],
            [0, 205, 867, 90],
            [0, 205, 867, 90],
            [0, 205, 867, 90],
            [0, 307, 867, 90],
            [0, 307, 867, 90],
            [0, 307, 867, 90]
        ],
        // To slow down the animation loop of the sprite, we set the frequency to 4 to slow down by a 4x factor
        animations: {
            stageanimation: [0, 11, "stageanimation"]
        }
    });
    stageSprite = new createjs.BitmapAnimation(stageSpriteSheet);
    stageSprite.x = 77;
    stageSprite.y = 534;
    
    stageSprite.gotoAndPlay("stageanimation");
    stage.addChild(stageSprite);


    log("Add light");
    topLightImgs = new Array();
    var positionLeft = 110;
    for (var i = 0; i < 3; i++) {
        topLightImgs[i] = new createjs.Bitmap(arrayImages[3]);
        topLightImgs[i].regX = 225;
        topLightImgs[i].regY = 13;
        topLightImgs[i].x = positionLeft;
        topLightImgs[i].y = -100;
        positionLeft += 400;
        topLightImgs[i].scaleX = 1.2;
        topLightImgs[i].scaleY = 1.2;
        stage.addChild(topLightImgs[i]);
    }


    log("Add logo");
    var logoSpriteSheet = new createjs.SpriteSheet({
        //image to use
        images: [arrayImages[4]],
        //width, height & registration point of each sprite
        frames: [
            [0, 0, 227, 386],
            [227, 0, 227, 386],
            [454, 0, 227, 386],
            [681, 0, 227, 386],
            [908, 0, 227, 386],
            [1135, 0, 227, 386],
            [1362, 0, 227, 386],
            [1599, 0, 227, 386]
        ],
        // To slow down the animation loop of the sprite, we set the frequency to 4 to slow down by a 4x factor
        animations: {
            stay: {
                frames: [0],
                next: "run",
                frequency: 2
            },
            run: {
                frames: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6]
            }
        }
    });
    logoSprite = new createjs.BitmapAnimation(logoSpriteSheet);
    logoSprite.x = 146;
    logoSprite.y = 18;
    logoSprite.gotoAndPlay("run");
    stage.addChild(logoSprite);

    
    log("Add Welcome lap character");
    var welcomeLapSpriteSheet = new createjs.SpriteSheet({
        //image to use
        images: [arrayImages[6]],
        //width, height & registration point of each sprite
        frames: { width: 139, height: 250, regX: 0, regY: 0, count: 110 },
        // To slow down the animation loop of the sprite, we set the frequency to 4 to slow down by a 4x factor
        animations: {
            lap: [0, 110, "lap"]
        }
    });
    welcomeLapSpite = new createjs.BitmapAnimation(welcomeLapSpriteSheet);

    welcomeLapSpite.x = 410;
    welcomeLapSpite.y = 200;
    welcomeLapSpite.scaleX = 1.5;
    welcomeLapSpite.scaleY = 1.5;
    welcomeLapSpite.gotoAndStop("lap");
    welcomeLapSpite.visible = false;
    stage.addChild(welcomeLapSpite);
    

    log("Add tvc Start character");
    var tvcStartSpriteSheet = new createjs.SpriteSheet({
        //image to use
        images: [arrayImages[7]],
        //width, height & registration point of each sprite
        frames: { width: 233, height: 250.5, regX: 0, regY: 0, count: 64 },
        // To slow down the animation loop of the sprite, we set the frequency to 4 to slow down by a 4x factor
        animations: {
            walk: [0, 64]
        }
    });
    tvcStartSpite = new createjs.BitmapAnimation(tvcStartSpriteSheet);

    tvcStartSpite.x = 520;
    tvcStartSpite.y = 200;
    tvcStartSpite.scaleX = 1.5;
    tvcStartSpite.scaleY = 1.5;
    tvcStartSpite.gotoAndStop("walk");
    tvcStartSpite.visible = false;
    stage.addChild(tvcStartSpite);
    

    createjs.Ticker.setFPS(8);
    createjs.Ticker.addEventListener("tick", tickHandle);

    setActiveTab($("#btnHome"));
    
    //var introVideo = document.getElementById("welcomeVideo");
    //var bitmap = new createjs.Bitmap(introVideo);
    //bitmap.x = 0;
    //bitmap.y = 300;
    //bitmap.scaleX = 0.5;
    //bitmap.scaleY = 0.5;
    //stage.addChild(bitmap);

    // welcomeVideoStart();
	$('#welcom').html('<img src="index_files/Welcome.gif" alt="" width="306" height="500" />');
	var myAudio = document.getElementById('sound-welcom').play();
    // myAudio.addEventListener('canplaythrough', function() {
      // this.currentTime = 12;
      // this.play();
    // });
}


/**
* Tick Handler
*/
var lightAngle = 2;
function tickHandle() {
    currentTick += 1;


    topLightImgs[0].rotation += lightAngle;
    topLightImgs[1].rotation -= lightAngle / 2;
    topLightImgs[2].rotation -= lightAngle;

    if (topLightImgs[0].rotation == 10)
        lightAngle = -2;
    else if (topLightImgs[0].rotation == -10)
        lightAngle = 2;



    if (currentTick > 8)
        currentTick = 0;
    

    if (tickTVC > -1) {
        if (tickTVC == 54) {
            showVideo("tvcVideo", tvcVideoEnd);
        }
        else
        if (tickTVC == 64) {
            tvcStartSpite.visible = false;
            tvcStartSpite.stop();
            tickTVC = -1;
            
            document.getElementById("tvcVideo").play();
        }
        tickTVC += 1;
    }
    stage.update();
}





/**
* Set tab active
*/
function setActiveTab(button) {
    $(".buttons button").removeClass("active");
    $(button).addClass("active");
}


/**
* Reset
*/
function reset() {
    stage.removeAllChildren();
    createjs.Ticker.removeAllListeners();
    stage.update();

}


/**
* log message
*/
function log(message) {
    console.log(message);
    $("#message").html(message);
}

function showVideo(videoid, nextFunction) {
    $("video").removeClass("videoActive");
    var video = document.getElementById(videoid);
    $(video).addClass("videoActive");

    droidfix.init(video);
    video.addEventListener("abort", nextFunction);
    droidfix.addEndListener(nextFunction);
}


function welcomeVideoStart() {
    pauseVideos();
    setActiveTab($("#btnHome"));
    showVideo("welcomeVideo", welcomeVideoEnd);
    document.getElementById("welcomeVideo").play();
}

function tvcVideoStart() {
    pauseVideos();
    setActiveTab($("#btnVideo"));
    $("video").removeClass("videoActive");
    //document.getElementById("tvcVideo").play();
    tvcStartSpite.visible = true;
    tvcStartSpite.play();
    tickTVC = 0;
}

function fullsongVideoStart() {
    pauseVideos();
    setActiveTab($("#btnMusic"));
    showVideo("fullsongVideo", fullsongVideoEnd);
    document.getElementById("fullsongVideo").play();
}

function welcomeVideoEnd() {
    log("Welcome video end");
    $("#welcomeVideo").removeClass("videoActive");
    welcomeLapSpite.visible = true;
    welcomeLapSpite.play();

}

function tvcVideoEnd() {
    log("TVC video end");
}

function fullsongVideoEnd() {
    log("Fullsong video end");
}

function pauseVideos() {
    document.getElementById("welcomeVideo").pause();
    document.getElementById("tvcVideo").pause();
    document.getElementById("fullsongVideo").pause();
    welcomeLapSpite.visible = false;
    welcomeLapSpite.stop();
    tvcStartSpite.visible = false;
    tvcStartSpite.stop();
    tickTVC = -1;
}